package com.lancoo.znbkxx.teacher.ui.fragment

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat.requestPermissions
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.base.userinfo.userinfosetting.base.Personalset
import com.lancoo.cpbase.authentication.activities.LoginActivity
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.cpbase.authentication.base.LoginOperate
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.PersonalCenterAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.base.SharedPreferencesHelper
import com.lancoo.znbkxx.teacher.databinding.FragmentPersonalCenterBinding
import com.lancoo.znbkxx.teacher.ui.activity.*
import com.lancoo.znbkxx.teacher.utils.ToastUtils
import com.lancoo.znbkxx.teacher.viewmodel.UserInfoViewModel
import com.lancoo.znbkxx.teacher.widget.GlideCircleWithBorder
import com.lancoo.znbkxx.teacher.widget.LogOutDialog


/**
 * @author : Admin
 * @date   : 2019/7/22 9:53
 * @desc   :
 */
class PersonalCenterFragment : BaseVMFragment<UserInfoViewModel, FragmentPersonalCenterBinding>(),
        BaseQuickAdapter.OnItemClickListener, View.OnClickListener {
    private val REQUEST_CALL_PERMISSION = 10111 //拨号请求码
    private val strList = listOf("关于", "日间模式", "设置")
    private lateinit var adapter: PersonalCenterAdapter
    private val personalSet: Personalset by lazy { Personalset() }
    private val mLoginOperate: LoginOperate by lazy { LoginOperate(activity) }
    private val mLogOutDialog: LogOutDialog by lazy {
        LogOutDialog.Builder(requireContext()).setMessage("您确定要退出登录吗?")
                .setCancleButton("取消") { dialog, _ -> dialog.dismiss() }
                .setEnsureButton("确定") { dialog, _ ->
                    dialog.dismiss()
                    mLoginOperate.logOut()
                    startActivity(Intent(activity, LoginActivity::class.java))
                    activity?.finish()
                }.create()
    }

    companion object {
        private const val TITLE = "title"
        fun newInstance(title: String): PersonalCenterFragment {
            val fragment = PersonalCenterFragment()
            val bundle = Bundle()
            bundle.putString(TITLE, title)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun providerContext(): Any? {
        return activity
    }

    override fun providerVMClass(): Class<UserInfoViewModel>? {
        return UserInfoViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.fragment_personal_center
    }

    override fun initView() {
        Log.e("initViewAA", "=======BASE_ADDRESS=========" + Ext.BASE_ADDRESS)
        binding.model = viewModel
        viewModel.PhotoPath.value = CurrentUser.getPhotoPath()
        viewModel.UserName.value = CurrentUser.getUserName()
        initList()
        binding.ivHead.setOnClickListener(this)
        binding.btnExit.setOnClickListener(this)
    }

    private fun initList() {
        adapter = PersonalCenterAdapter(strList)
        adapter.onItemClickListener = this
        val manager = GridLayoutManager(requireContext(), 4)
        binding.rv.layoutManager = manager
        binding.rv.adapter = adapter
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.iv_head -> personalSet.goToUserInfoActivity(activity, Ext.BASE_ADDRESS,
                    CurrentUser.Token, CurrentUser.UserID)
//            R.id.rl_set -> personalSet.goToSafeActivity(activity, Ext.BASE_ADDRESS,
//                    CurrentUser.Token, CurrentUser.UserType)
//            R.id.rl_help -> startActivity(Intent(activity, HelpActivity::class.java))
//            R.id.rl_analysis -> startActivity(Intent(activity, AnalysisActivity::class.java))
//            R.id.rl_assess -> startActivity(Intent(activity, AssessActivity::class.java))
            //            R.id.rl_prediction->startActivity(Intent(activity, PredictionActivity::class.java))
            R.id.btn_exit -> mLogOutDialog.show()

//            R.id.rl_service_agreement -> startActivity(
//                    Intent(activity, PrivacyActivity::class.java).apply {
//                        putExtra("isPrivacy", false)
//                    })
//            R.id.rl_privacy_policy -> startActivity(
//                    Intent(activity, PrivacyActivity::class.java).apply {
//                        putExtra("isPrivacy", true)
//                    })
//            R.id.call_tv -> onCall("4006986166")
        }
    }

    //设置头像
    private fun setAvatar() {
        Glide.with(requireContext()).load(CurrentUser.PhotoPath).apply(
                RequestOptions().error(
                        ResourcesCompat.getDrawable(requireContext().resources, R.mipmap.icon_head,
                                null))
                        .centerCrop().diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .transform(GlideCircleWithBorder(3, R.color.white))).into(binding.ivHead)
    }

    override fun onResume() {
        super.onResume()
        resultRefreshHeadImage()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CALL_PERMISSION) {
            if (permissions.isNotEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED) { //失败
//                Toast.makeText(activity, "请允许拨号权限后再试", Toast.LENGTH_SHORT).show()
                MyToast.showToast("请允许拨号权限后再试")
            } else { //成功
                onCall("4006986166")
            }
        }
    }

    /**
     * 判断是否有某项权限
     *
     * @param string_permission 权限
     * @param request_code      请求码
     * @return
     */
    private fun checkReadPermission(string_permission: String, request_code: Int): Boolean {
        var flag = false
        if (ContextCompat.checkSelfPermission(requireActivity(),
                        string_permission) == PackageManager.PERMISSION_GRANTED) { //已有权限
            flag = true
        } else { //申请权限
            requestPermissions(requireActivity(), arrayOf(string_permission), request_code)
        }
        return flag
    }

    /**
     * 拨打电话（直接拨打）
     *
     * @param telPhone 电话
     */
    private fun onCall(telPhone: String) {
        if (checkReadPermission(Manifest.permission.CALL_PHONE, 10111)) {
            val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$telPhone"))
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }
    }

    private fun resultRefreshHeadImage() {
        viewModel.PhotoPath.value = CurrentUser.PhotoPath
        viewModel.UserName.value = CurrentUser.UserName
//        setAvatar()
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val intent = Intent()
        when (position) {
            0 -> {
                intent.setClass(requireContext(), HelpActivity::class.java)
                startActivity(intent)
            }
            1 -> {
                val isHealthEye = SharedPreferencesHelper.getBoolean("stuhealtheye", false)
                if (!isHealthEye) {
                    SharedPreferencesHelper.applyBoolean("stuhealtheye", true)
                    view?.findViewById<ImageView>(R.id.iv)
                            ?.setImageResource(R.mipmap.icon_nightmode)
                    view?.findViewById<TextView>(R.id.tv)?.text = "夜间模式"
                    openAleterWindow()
                } else {
                    SharedPreferencesHelper.applyBoolean("stuhealtheye", false)
                    view?.findViewById<ImageView>(R.id.iv)?.setImageResource(R.mipmap.icon_daymode)
                    view?.findViewById<TextView>(R.id.tv)?.text = "日间模式"
                    closeHealthEye()
                }
            }
            2 -> {
                personalSet.goToSafeActivity(activity, Ext.BASE_ADDRESS, CurrentUser.Token,
                        CurrentUser.UserType)
            }
        }
    }

}